<?php
class Template extends Model{
	public $_table = 'tpl';

	public function addModel(){
		$title = isset($_POST['title'])?(Character::HTMLToDbEncode($_POST['title'])):'';
		$path = isset($_POST['path'])?(Character::HTMLToDbEncode($_POST['path'])):'';

		$arr = array(
			'`title`'=>"'{$title}'",
			'`path`'=>"'{$path}'",
		);
		return $this->add($arr);
	}

	public function updateMode($id){
		$title = isset($_POST['title'])?(Character::HTMLToDbEncode($_POST['title'])):'';
		$path = isset($_POST['path'])?(Character::HTMLToDbEncode($_POST['path'])):'';

		$arr = array(
			'title'=>"{$title}",
			'path'=>"{$path}",
		);
		$this->update($arr,'id='.$id);

		$this->updateHtml($id);
	}

	public function updateTplModel($id){
		$tpl = isset($_POST['tpl'])?$_POST['tpl']:'';
		$tpl = Character::HTMLToDbEncode($tpl);
		$arr = array(
			'tpl'=>"{$tpl}"
		);
		$this->update($arr,'id='.$id);
		$this->updateHtml($id);
	}

	public function getOneData($id){
		$sql = "select * from {$this->_table} where `id`=".intval($id);
		return $this->getOne($sql);
	}

	public function updateHtml($id){
		$data = $this->getOneData($id);
		$html = $this->parse($data['tpl'],$id);
		$arr = array( 'html'=>Character::HTMLToDbEncode($html));
		$this->update($arr,'id='.$id);
		
		// 生成文件
		$path = $data['path'];
		file_put_contents(WEB_ROOT.$path,$html);
	}

	// 模版字符解析
	private function parse($str,$tpl_id){
		$m = Core::getInstance()->app_load_class('WebDataBlock');
		$r = Core::getInstance()->app_load_class('Relate');
		$str = Character::HTMLToDbDecode($str);
		if(preg_match_all("/{([^}]*)}/i",$str,$matches)){
			$iLen = count($matches[0]);
			$arr = array();
			for($i=0;$i<$iLen;$i++){
				$id = $matches[1][$i];
				$t = $m->getOneData($id);
				if(isset($t) && !empty($t)){
				   	$arr[$matches[0][$i]] = Character::HTMLToDbDecode($t['html']);
					$r->relateData($id,$tpl_id);
				}
				unset($t);
			}
			$search = array_keys($arr);
			$str = str_replace($search,$arr,$str);
			return $str;
		}
		return $str;
	}

	public function delData($id){
		$this->del($id);
	}
}
